
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>DashBoard</title>
    <!--引入js-->
    <script src="/js/socket.io.js"></script>
    <script src="/js/jquery-3.1.1.min.js"></script>
    <script src="/js/highcharts.js"></script>
    <script src="/js/exporting.js"></script>
    <style>
        body {
            display: flex;
            flex-wrap: wrap;
            margin: 0;
            padding: 0;
        }
        .chart-container {
                     border: 1px solid #ccc;
                     box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                     box-sizing: border-box;
                     height: 350px;
                     margin: 5px;
                 }
        .chart-container:nth-child(-n + 3) {
            width: calc(33.33% - 10px);
        }
        .chart-container:nth-child(n + 4) {
            width: calc(50% - 10px);
        }
    </style>
    <script type="text/javascript">
        //柳炎炎
        // 用于存储女性count总和
        var femaleCountSum = 0;
        // 用于存储男性count总和
        var maleCountSum = 0;

        // 杨茗茹
        var studentData = {
            A: { male: 0, female: 0 },
            L: { male: 0, female: 0 }
        };

        // 张羿婷
        var classData = {};

        // 孟佳怡
        var semesterData = {};

        // 李一鸣
        var semesterclassData = {};

        // 连接
        var socket = io.connect('127.0.0.1:7777');

        // 处理 stumsg 事件（柳炎炎）
        socket.on('stumsg', function (message) {
            console.log("柳炎炎")
            console.log(message);
            var dataArray = message.split(':');
            console.log(dataArray);
            var data=dataArray[1].split(',')
            var maleCount = 0;
            var femaleCount = 0;
            if (data.length === 2) {
                if (data[0] ==='male') {
                    maleCount = parseInt(data[1]);
                } else if (data[0] === 'female') {
                    femaleCount = parseInt(data[1]);
                }
            }
            // 累加女性 count 总和
            if (femaleCount >= 0) {
                femaleCountSum += femaleCount;
            }
            // 累加男性 count 总和
            if (maleCount >= 0) {
                maleCountSum += maleCount;
            }
        });

        //杨茗茹
        // 处理 statemsg 事件（不同学籍状态性别统计，对应之前杨茗茹相关功能）
        socket.on('statemsg', function (message) {
            console.log("杨茗茹");
            console.log(message);
            var dataArray = message.split(':');
            var data = dataArray[1].split(',');
            if (data.length === 3) {
                var state = data[0];
                var gender = data[1];
                var count = parseInt(data[2]);
                if (!studentData[state]) {
                    studentData[state] = { male: 0, female: 0 };
                }
                if (gender === 'male') {
                    studentData[state].male += count;
                } else if (gender === 'female') {
                    studentData[state].female += count;
                }
            }
        });
        //
        //张羿婷
        socket.on('classmsg', function (message) {
            console.log("张弈婷", message);
            var dataArray = message.split(',');
            if (dataArray.length === 3) {
                var class_name = dataArray[0];
                var gender = dataArray[1];
                var count = parseInt(dataArray[2]);
                if (!classData[class_name]) {
                    classData[class_name] = { maleSum: 0, femaleSum: 0 };
                }
                if (gender ==='male') {
                    classData[class_name].maleSum += count;
                } else if (gender === 'female') {
                    classData[class_name].femaleSum += count;
                }
                updateClassChart();
            }
        });

        //孟佳怡
        socket.on('semetermsg', function (message) {
            console.log("孟佳怡", message);
            var dataArray = message.split(',');
            if (dataArray.length === 3) {
                var semeter = dataArray[0];
                var gender = dataArray[1];
                var count = parseInt(dataArray[2]);
                if (!semesterData[semeter]) {
                    semesterData[semeter] = { maleSum: 0, femaleSum: 0 };
                }
                if (gender ==='male') {
                    semesterData[semeter].maleSum += count;
                } else if (gender === 'female') {
                    semesterData[semeter].femaleSum += count;
                }
                updateSemesterChart();
            }
        });
        // 李一鸣
        socket.on('semesterclassmsg', function (message) {
            console.log("李一鸣:", message);
            var dataArray = message.split(':');
            var data = dataArray[1].split(',');
            if (data.length === 4) {
                var class_id = data[0];
                var semester = data[1];
                var gender = data[2];
                var count = parseInt(data[3]);
                if (!semesterclassData[class_id]) {
                    semesterclassData[class_id] = {};
                }
                if (!semesterclassData[class_id][semester]) {
                    semesterclassData[class_id][semester] = { maleSum: 0, femaleSum: 0 };
                }
                if (gender ==='male') {
                    semesterclassData[class_id][semester].maleSum += count;
                } else if (gender === 'female') {
                    semesterclassData[class_id][semester].femaleSum += count;
                }
                updateChart();
            }
        });
        // 班级性别统计：初始化图表函数 张羿婷
        function initClassChart() {
            return Highcharts.chart('class_container', {
                chart: {
                    type: 'bar',
                    animation: Highcharts.svg,
                    marginRight: 10
                },
                title: {
                    text: '实时班级男女生人数统计'
                },
                xAxis: {
                    title: {
                        text: '班级'
                    },
                    categories: []
                },
                yAxis: {
                    title: {
                        text: '人数总和'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }],
                    allowDecimals: false
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                            this.x + '<br/>' +
                            Highcharts.numberFormat(this.y, 0);
                    }
                },
                legend: {
                    enabled: true
                },
                exporting: {
                    enabled: true
                },
                plotOptions: {
                    series: {
                        animation: {
                            duration: 1000
                        },
                        stacking: 'normal'
                    }
                },
                series: [{
                    name: '女生人数',
                    data: [],
                    color: 'pink'
                },
                    {
                        name: '男生人数',
                        data: [],
                        color: 'blue'
                    }]
            });
        }

        // 班级性别统计：更新图表数据的函数 张羿婷
        function updateClassChart() {
            var chart = Highcharts.charts['class_container'];
            if (!chart) {
                chart = initClassChart();
            }
            var classes = Object.keys(classData);
            chart.xAxis[0].setCategories(classes);

            var femaleSeries = chart.series[0];
            var maleSeries = chart.series[1];
            classes.forEach(function (class_name) {
                var femaleSum = classData[class_name]? classData[class_name].femaleSum : 0;
                var maleSum = classData[class_name]? classData[class_name].maleSum : 0;
                femaleSeries.addPoint([class_name, femaleSum], true, false);
                maleSeries.addPoint([class_name, maleSum], true, false);
            });
            chart.redraw();
        }

        // 学期性别统计：初始化图表函数 孟佳怡
        function initSemesterChart() {
            return Highcharts.chart('semester_container', {
                chart: {
                    type: 'bar',
                    animation: Highcharts.svg,
                    marginRight: 10
                },
                title: {
                    text: '不同学期男女生人数统计'
                },
                xAxis: {
                    title: {
                        text: '学期'
                    },
                    categories: []
                },
                yAxis: {
                    title: {
                        text: '人数总和'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }],
                    allowDecimals: false
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                            this.x + '<br/>' +
                            Highcharts.numberFormat(this.y, 0);
                    }
                },
                legend: {
                    enabled: true
                },
                exporting: {
                    enabled: true
                },
                series: [{
                    name: '女生人数',
                    data: [],
                    color: 'green',
                    stacking: 'normal'
                },
                    {
                        name: '男生人数',
                        data: [],
                        color: 'purple',
                        stacking: 'normal'
                    }]
            });
        }

        // 学期性别统计：更新图表数据的函数 孟佳怡
        function updateSemesterChart() {
            var chart = Highcharts.charts['semester_container'];
            if (!chart) {
                chart = initSemesterChart();
            }
            var semesters = Object.keys(semesterData);
            chart.xAxis[0].setCategories(semesters);

            var femaleSeries = chart.series[0];
            var maleSeries = chart.series[1];
            semesters.forEach(function (semeter) {
                var femaleSum = semesterData[semeter]? semesterData[semeter].femaleSum : 0;
                var maleSum = semesterData[semeter]? semesterData[semeter].maleSum : 0;
                femaleSeries.addPoint([semeter, femaleSum], true, false);
                maleSeries.addPoint([semeter, maleSum], true, false);
            });
            chart.redraw();
        }
        // 初始化图表函数 李一鸣
        function initChart() {
            return Highcharts.chart('li_container', {
                chart: {
                    type: 'pie',
                    animation: {
                        duration: 1000 // 设置动画持续时间为1秒
                    }
                },
                title: {
                    text: '实时班级不同学期男女生人数统计'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
                series: [{
                    name: '人数比例',
                    data: []
                }]
            });
        }
        // 更新图表数据的函数 李一鸣
        function updateChart() {
            var chart = Highcharts.charts['li_container'];
            if (!chart) {
                chart = initChart();
            }
            var data = [];
            for (var class_id in semesterclassData) {
                for (var semester in semesterclassData[class_id]) {
                    var maleSum = semesterclassData[class_id][semester].maleSum;
                    var femaleSum = semesterclassData[class_id][semester].femaleSum;
                    var total = maleSum + femaleSum;
                    if (total > 0) {
                        var malePercent = (maleSum / total) * 100;
                        var femalePercent = (femaleSum / total) * 100;
                        data.push({
                            name: class_id + '-' + semester +'男生',
                            y: malePercent
                        });
                        data.push({
                            name: class_id + '-' + semester +'女生',
                            y: femalePercent
                        });
                    }
                }
            }
            chart.series[0].setData(data, true, true); // 启用数据更新动画
        }

        window.onload = function () {
            Highcharts.setOptions({
                global: {
                    // 设置时间，使用本地时间
                    useUTC: false
                }
            });

            // 整体男女生人数实时分析图表（柳炎炎）
            // 设置Highcharts图标spline在#container中显示
            var chart = Highcharts.chart('stumsg_container', {
                chart: {
                    // 带标记曲线图
                    type: 'spline',
                    animation: Highcharts.svg,
                    marginRight: 10,
                    events: {
                        // 加载事件
                        load: function () {
                            // 获取女生数据
                            var series1 = this.series[0];
                            // 获取男生数据
                            var series2 = this.series[1];

                            // 定时器，每两秒执行一次
                            setInterval(function () {

                                var x = (new Date()).getTime();

                                // 处理女性数据
                                series1.addPoint([x, femaleCountSum], true, true);

                                // 处理男性数据
                                series2.addPoint([x, maleCountSum], true, true);
                            }, 2000);
                        }
                    }
                },
                title: {
                    text: '男女生人数实时分析'
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 50
                },
                yAxis: {
                    title: {
                        text: '数量'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }],
                    allowDecimals: false
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                            Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
                            Highcharts.numberFormat(this.y, 0);
                    }
                },
                legend: {
                    enabled: true
                },
                exporting: {
                    enabled: true
                },
                series: [{
                    name: '女生人数',
                    data: (function () {
                        // 生成一个长度为20，值为随机数的数组，作为初始数据显示
                        var data = [],
                            time = (new Date()).getTime(),
                            i;
                        for (i = - 19; i <= 0; i += 1) {
                            data.push({
                                x: time + i * 1000,
                                y: Math.random()
                            });
                        }
                        return data;
                    }())
                },
                    {
                        name: '男生人数',
                        data: (function () {

                            var data = [],
                                time = (new Date()).getTime(),
                                i;

                            for (i = - 19; i <= 0; i += 1) {
                                data.push({
                                    x: time + i * 1000,
                                    y: Math.random()
                                });
                            }
                            return data;
                        }())
                    }]
            });

            // 不同学籍状态男女生人数实时分析图表（杨茗茹）
            var chart = Highcharts.chart('state_container', {
                chart: {
                    // 带标记曲线图
                    type: 'spline',
                    animation: Highcharts.svg,
                    marginRight: 10,
                    events: {
                        // 加载事件
                        load: function () {
                            // 获取学籍A女生数据
                            var series1 = this.series[0];
                            // 获取学籍A男生数据
                            var series2 = this.series[1];
                            // 获取学籍L女生数据
                            var series3 = this.series[2];
                            // 获取学籍L男生数据
                            var series4 = this.series[3];

                            // 定时器，每两秒执行一次
                            setInterval(function () {

                                var x = (new Date()).getTime();

                                // 处理学籍A女生数据
                                series1.addPoint([x, studentData['A'].female], true, true);

                                // 处理学籍A男生数据
                                series2.addPoint([x, studentData['A'].male], true, true);

                                // 处理学籍L女生数据
                                series3.addPoint([x, studentData['L'].female], true, true);

                                // 处理学籍L男生数据
                                series4.addPoint([x, studentData['L'].male], true, true);
                            }, 2000);
                        }
                    }
                },
                title: {
                    text: '不同学籍男女生人数实时分析'
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 50
                },
                yAxis: {
                    title: {
                        text: '数量'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }],
                    allowDecimals: false
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                            Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
                            Highcharts.numberFormat(this.y, 0);
                    }
                },
                legend: {
                    enabled: true
                },
                exporting: {
                    enabled: true
                },
                series: [
                    {
                        name: '学籍A女生人数',
                        data: (function () {
                            // 生成一个长度为20，值为随机数的数组，作为初始数据显示
                            var data = [],
                                time = (new Date()).getTime(),
                                i;
                            for (i = - 19; i <= 0; i += 1) {
                                data.push({
                                    x: time + i * 1000,
                                    y: Math.random()
                                });
                            }
                            return data;
                        }())
                    },
                    {
                        name: '学籍A男生人数',
                        data: (function () {
                            // generate an array of random data
                            var data = [],
                                time = (new Date()).getTime(),
                                i;

                            for (i = - 19; i <= 0; i += 1) {
                                data.push({
                                    x: time + i * 1000,
                                    y: Math.random()
                                });
                            }
                            return data;
                        }())
                    },
                    {
                        name: '学籍L女生人数',
                        data: (function () {
                            // 生成一个长度为20，值为随机数的数组，作为初始数据显示
                            var data = [],
                                time = (new Date()).getTime(),
                                i;
                            for (i = - 19; i <= 0; i += 1) {
                                data.push({
                                    x: time + i * 1000,
                                    y: Math.random()
                                });
                            }
                            return data;
                        }())
                    },
                    {
                        name: '学籍L男生人数',
                        data: (function () {
                            // generate an array of random data
                            var data = [],
                                time = (new Date()).getTime(),
                                i;

                            for (i = - 19; i <= 0; i += 1) {
                                data.push({
                                    x: time + i * 1000,
                                    y: Math.random()
                                });
                            }
                            return data;
                        }())
                    }
                ]
            });
            updateClassChart();
            updateSemesterChart();
            updateChart();
        };
    </script>

</head>

<body>

<div class="chart-container" id="class_container"></div>
<div class="chart-container" id="li_container"></div>
<div class="chart-container" id="semester_container"></div>
<div class="chart-container" id="stumsg_container"></div>
<div class="chart-container" id="state_container"></div>
</body>

</html>
